﻿using UnityEngine;
using System.Collections;
using System.Collections.Concurrent;
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;


public class XinyueGameClient : MonoBehaviour
{
    public static XinyueGameClient instance;
    private XinyueSocketClient socketClient;
    private HeartbeatManager heartbeatManager;
    private  RequestMessageManager requestMessageManager;
    private  ResponseMessageManager responseMessageManager;
    private  ReadSocketDataManager readSocketDataManager;

    public string host;
    public int port;

    public RequestMessageManager RequestMessageManager { get => requestMessageManager; }
    public ResponseMessageManager ResponseMessageManager { get => responseMessageManager;}

    public event OnConnectedServerEventHandler ConnectEventHandler;
    private volatile ConnectedStatus connectedStatus = ConnectedStatus.Default;

    
    public static XinyueGameClient Instance()
    {
        return instance;
    }

     void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
        instance = this;
        socketClient = new XinyueSocketClient(host, port);
        socketClient.CompleteConnectServerHandler += OnConnectStatusChange;
        requestMessageManager = new RequestMessageManager(socketClient);
        readSocketDataManager = new ReadSocketDataManager(socketClient);
        responseMessageManager = new ResponseMessageManager(readSocketDataManager, RequestMessageManager);
        heartbeatManager = new HeartbeatManager(socketClient, readSocketDataManager);
    }

    public void OnConnectStatusChange(ConnectedStatus connectedStatus)
    {
        this.connectedStatus = connectedStatus;
    }
    
    public void StartConnectServer()
    {
        socketClient.ConnectServer();
    }


    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if(connectedStatus != ConnectedStatus.Default)
        {
            
            ConnectEventHandler?.Invoke(connectedStatus);
            connectedStatus = ConnectedStatus.Default;
        }
        requestMessageManager.Update();
        responseMessageManager.Update();
        heartbeatManager.Update();
    }
}
